package com.example.demo.handler;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.example.demo.config.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: springboot
 * @author: daPangDong
 * @create: 2022-06-01 10:34
 */

//@ControllerAdvice(basePackages = {"com.example.demo.controller"})
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
    @ControllerAdvice 捕获 Controller 层抛出的异常，如果添加 @ResponseBody 返回信息则为JSON格式。
    @RestControllerAdvice 相当于 @ControllerAdvice 与 @ResponseBody 的结合体。
    @ExceptionHandler 统一处理同种类的异常，减少代码重复率，降低复杂度。
     */
//    private static final Log log = LogFactory.get();
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 统一异常处理@ExceptionHandler,主要用于Exception
     * @param request 请求
     * @param exception 异常
     * @return 返回结果
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result<?> error(HttpServletRequest request, Exception exception) {
        log.error("请求URL：{}", request.getRequestURL());
        log.error("异常信息：", exception);
        return Result.error(-1,"异常", exception.getMessage(),request.getRequestURI());
    }


}
